#! /usr/bin/env python

############### L I C E N C E ################
# This is BSD licenced software, and as such:
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Or put in the laymans words: "You use, your responsibility."
#
# Copyright (C) H. Lindqvist 2005, 2006, 2007.
#
#


import marshal, sys, os, os.path

b = os.environ['HOME'] + '/.b'
brc = b + '/books'

if not os.path.isdir(b):
    os.makedirs(b)

try:
    if not os.path.isfile(brc):
        fd = open(brc, 'w+b')
    else:
        fd = open(brc, 'r+b')

except:
    sys.stderr.write('Failed to open bookmark file\n')
    sys.exit(1)

try:
    books = marshal.load(fd)
except:
    books = {}

fd.close()
sys.argv = sys.argv[1:]
usage = 'Usage: b [add <short> <bookmark>] [del <short>] [list] [short]'

if len(sys.argv) == 0:
    sys.stderr.write(usage + '\n')

elif sys.argv[0] == 'add':
    if len(sys.argv) == 3:
        try:
            p = os.path.realpath(sys.argv[2])
            if os.path.isfile(p) or os.path.isdir(p):
                books[sys.argv[1]] = p
                print 'Added: ' + sys.argv[1] + ' -> ' + p
            else:
                sys.stderr.write('Not a file or dir: ' + p + '\n')
        except KeyError:
            sys.stderr.write('Error adding bookmark\n')
    else:
        sys.stderr.write(usage + '\n')

elif sys.argv[0] == 'del':
    if len(sys.argv) == 2:
        try:
            del books[sys.argv[1]]
            print 'Deleted: ' + sys.argv[1]
        except KeyError:
            sys.stderr.write('Error deleting bookmark\n')
    else:
        print usage

elif sys.argv[0] == 'list':
    if len(sys.argv) == 1:
        try:
            print 'Bookmarks:'
            for x in books.keys():
                print '  ' + x + ' : ' + books[x]
        except KeyError, (errno, strerror):
            sys.stderr.write('Error getting list\n')

elif len(sys.argv) == 1:
    try:
        print books[sys.argv[0]]
    except:
        sys.stderr.write('No such bookmark\n')

else:
    sys.stderr.write(usage + '\n')

if len(sys.argv) > 1:
    try:
        fd = open(brc, 'r+')
        marshal.dump(books, fd)
        fd.close()
    except:
        print 'Failed to store bookmark file'
